package com.emo.wowoblog.controller;


import com.emo.wowoblog.entity.Article;
import com.emo.wowoblog.service.ArticleService;
import com.emo.wowoblog.utils.Pager;
import com.emo.wowoblog.view.ArticleView;
import com.emo.wowoblog.vo.HttpResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private ArticleService articleService;

    @Value("${mypager.perPagerSize}")
    private final int PER_PAGE_SIZE = 5 ;
    //发新博文
    @PostMapping("post")
    public Map<String,Object> post(Article article){
        try{
            article.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            article.setModifyTime(article.getCreateTime());
            articleService.save(article);
            return HttpResult.success(article);
        }
        catch(Exception ex){
            ex.printStackTrace();
            return HttpResult.fail("发表博文失败。");
        }

    }

    @GetMapping("queryAll")
    public Map<String,Object> queryAllArticles(){
        try{
            Pager<ArticleView> articleViewPager = new Pager<ArticleView>();
            articleViewPager.setCountPerpage(10);
            articleViewPager.setCurentPageIndex(1);
            List<ArticleView> articleList = articleService.queryAllArticlePager(articleViewPager);
            return HttpResult.success(articleList);
        }
        catch(Exception ex){
            ex.printStackTrace();
            return HttpResult.fail("查询博文列表失败。");
        }
    }

    @GetMapping("queryById/{aid}")
    public Map<String,Object> queryById(@PathVariable(name="aid") String aid){

        try{
           ArticleView a = articleService.queryArticleViewByAid(Integer.parseInt(aid));
           return  HttpResult.success(a);
        }
        catch(Exception ex){
            ex.printStackTrace();
            return HttpResult.fail();
        }
    }
}
